package cn.thr.ymcc.filter;

import cn.thr.ymcc.config.ExcludeProperties;
import cn.thr.ymcc.jwt.*;
import cn.thr.ymcc.result.JsonResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.List;
import java.util.Properties;

/**
 * 身份认证拦截
 * 获取请求头种的U-TOKEN，利用jwt 工具类使用用公钥解密，判断载荷数据非空
 */
@Component
public class AuthenticationFilter implements GlobalFilter, Ordered {


    @Value("${jwt.rsa.pub}")
    private String pub;
    @Autowired
    private ExcludeProperties excludeProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //响应对象
        ServerHttpResponse response = exchange.getResponse();
        //载荷数据为空，表示未登录 发回给前端NOLogin
        DataBuffer buffer = null;

        try {
            //0.放行yml路径配置中配置需要放行的所有接口地址
            if(excludeProperties.isExcluded(exchange.getRequest().getPath().value())){
                return chain.filter(exchange);
            }

            //1.获取请求头
            List<String> headers = exchange.getRequest().getHeaders().get(LoginContextUtils.JWT_TOKEN_NAME);

            //判断获取请求头 里面有没有数据  size()List 返回的长度
            if(headers != null && headers.size() >0){
                //拿list 里面的第一个
                String jwtToken = headers.get(0);
                //2.使用工具类来公钥解密
                PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(pub).getFile());
                //取出token 和公钥
                Payload<PayloadData> payload = JwtUtils.getInfoFromToken(jwtToken, publicKey, PayloadData.class);
                if(payload != null && payload.getUserInfo() != null && payload.getUserInfo().getLogin() != null){
                    //载荷payload 非空就是登录成功 ， 直接放行
                    return chain.filter(exchange);
                }
            }
            byte[] bytes = JSON.toJSONString(JsonResult.error("noLogin")).getBytes("utf-8");
            buffer = response.bufferFactory().wrap(bytes);
            //设置完成相应，不会继续执行后面的filter
            //response.setComplete();
            //response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //把结果写给客户端
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
